﻿#define DEBUG_AGENT

using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Xml.Linq;
using tnet.Controls.Lookless;
using tnet.Model;
using Microsoft.Advertising.Mobile.UI;
using Microsoft.Devices;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;

// xaml tile?
namespace tnet
{
    public partial class MainPage : PhoneApplicationPage
    {
        #region // members //

        // data   
        private String _BlogRSS = "http://208.113.144.166/?feed=rss2";
        //private String _TwitterRSS = "http://twitter.com/statuses/user_timeline/DavidJKelley.rss";
        private String _WorkEmail = "pratoriate@gmail.com";
        private String _HomeEmail = "pratoriate@gmail.com";
        private String _AdminEmail = "pratoriate@gmail.com";
        private String _EmailSubject = "";
        private String _AdminEmailSubject = "Email From Transhumanity.net The App on WP";
        private String _RootURL = "http://208.113.144.166/";
        private String _PhoneNumber = "8887272325"; // the show...
        private String _Box1Name = "www.transhumanity.net";
        private String _Box1URL = "http://208.113.144.166/";
        private String _Box2Name = "www.transhumanity.net";
        private String _Box2URL = "http://208.113.144.166/";
        private String _Box3Name = "www.transhumanity.net";
        private String _Box3URL = "http://208.113.144.166/";
        private String _EmailSubjectPrefix = "T.NET for WP: ";
        private String TwitterHandle = "DavidJKelley";
        private String _CallTileText = "Call Transhumanity.net";
        private String _RegularTileTitle = "Transhumanity.net";
        private String _NewTileBackTitle = "Transhumanity.net";
        private String _AboutText = "What is transhumanism? What are we about? If your here maybe your new to transhumanism, interested in what it is about and why we all care?  For transhumanists like me its about helping others and becoming more then what we are now and working towards transcending our biology. Lets start with what is transhumanism' in simplest terms it is the idea that human kind can use science and technology to become more then what we are and help those interested in doing the same and in protecting the freedom for all to decide for themselves how to be happy in other words 'live liberty and the pursuit of happiness'. Transhumanism is not a single demographic.  Some transhumanists are political, some are not, some are religious, and some are not.  In transhumanism, democrats, republicans, libertarians, Europeans, Americans, Chinese, Mormons, Catholics, Muslims, Buddhists, Atheist and more; come together as “humans” to help others and raise as many as want as high as possible through the use of technology and science.  We believe in better education, higher standards in living and longer lives and in our moral and ethical responsibility to the same. But what about this site?  The history is thus, in its short stay it has had its up’s and downs.  Currently owned and operated by the Foundation as a way to help people understand transhumanism, a sort of embassy to the rest of humanity and a hub for all things transhuman.  So what is the history of Transhumanity.net: Transhumanity.net was set by by Hank Pellissier in October 2012.  'TNet' advocates for a world where suffering is eliminated, aid to the disadvantaged is encouraged, and societies that provide justice, equality, and liberty for all are the norm.  In late 2013 ZeroState took over operating the site and in June of 2014 the Foundation took over operating the site, migrating it to word press and re-launching in August 2014 in its present form. We are always looking for help, articles, volunteers anything that helps us help others.  please reach out to us";
        private String _NewsUpdates = "checking for news updates";
        private String _BackTileTitle = "Transhumanity.net";
 
        private VibrateController _Vibration = VibrateController.Default;
        private TimeSpan _ThisTime = new TimeSpan(0, 0, 0, 0, 30);

        private int _NewsCounter = 0;

        private ResourceIntensiveTask resourceIntensiveTask;
        private String resourceIntensiveTaskName = "CheckNewsItemTask"; 

        #endregion  
          
        public MainPage()
        {
            InitializeComponent();

            Application.Current.Host.Settings.EnableFrameRateCounter = false;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            AdControl.TestMode = false;

            // loads cached data
            PreloadAnimation.Begin();

            PopulateSavedValues();

            // blog rss
            WebClient TwitterClient = new WebClient();
            TwitterClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ResponseHandler);
            TwitterClient.DownloadStringAsync(new Uri(_BlogRSS));

            #region //define default tile

            ShellTile TileToFind = ShellTile.ActiveTiles.First();

            if (TileToFind != null)
            { 
                StandardTileData NewTileData = new StandardTileData();

                NewTileData.Title = _RegularTileTitle;
                NewTileData.BackgroundImage = new Uri("Resources/Tile.180.jpg", UriKind.Relative);
                NewTileData.Count = 0;
                NewTileData.BackTitle = "";
                NewTileData.BackBackgroundImage = new Uri("Resources/gbtv.jpg", UriKind.Relative);

                TileToFind.Update(NewTileData);
            }

            #endregion

            // any specialized tasks...
            String SpecialTask = "";
            if (NavigationContext.QueryString.TryGetValue("Task", out SpecialTask))
            {
                switch (SpecialTask)
                {
                    case "2":
                        ExecuteCall(_PhoneNumber);
                        break;
                }
            }

            String Temp = Tools.GetSetting("_NewsCounter").ToString();
            if (String.IsNullOrEmpty(Temp))
            {
                Temp = "0";
            }

            _NewsCounter = int.Parse(Temp);
            if (_NewsCounter <= 0)
            {
                Tools.SaveSetting("_NewsCounter", "0");
            }

            StartResourceIntensiveAgent(); 
        }
        
        private void RemoveAgent(String name)
        {
            try
            {
                ScheduledActionService.Remove(name);
            }
            catch (Exception)  { }
        }

        private void StartResourceIntensiveAgent()
        {  
            resourceIntensiveTask = ScheduledActionService.Find(resourceIntensiveTaskName) as ResourceIntensiveTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update 
            // the schedule.
            if (resourceIntensiveTask != null)
            {
                RemoveAgent(resourceIntensiveTaskName);
            }

            resourceIntensiveTask = new ResourceIntensiveTask(resourceIntensiveTaskName);
            resourceIntensiveTask.Description = _NewsUpdates; 

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(resourceIntensiveTask); 

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if(DEBUG_AGENT)
                ScheduledActionService.LaunchForTest(resourceIntensiveTaskName, TimeSpan.FromSeconds(5));
#endif
            }
            catch (InvalidOperationException) { }
            catch (SchedulerServiceException) { } 
        }
         
        private String CheckAndDefaultValue(String InputValue, String KeyValue)
        {
            String Temp = InputValue;
            InputValue = Tools.GetSetting(KeyValue);
            if (String.IsNullOrEmpty(InputValue))
            {
                InputValue = Temp;
            }
            return InputValue;
        }

        private void PopulateSavedValues()
        {
            _Box1Name = CheckAndDefaultValue(_Box1Name, "_Box1Name");
            _Box1URL = CheckAndDefaultValue(_Box1URL, "_Box1URL");
            _Box2Name = CheckAndDefaultValue(_Box2Name, "_Box2Name");
            _Box2URL = CheckAndDefaultValue(_Box2URL, "_Box2URL");
            _Box3Name = CheckAndDefaultValue(_Box3Name, "_Box3Name");
            _Box3URL = CheckAndDefaultValue(_Box3URL, "_Box3URL");

            ThirdItemTxt.Text = _Box3Name;
            ThirdItemTxt.Tag = _Box3URL; 
            NextNewsTxt.Text = _Box2Name;
            NextNewsTxt.Tag = _Box2URL; 
            TopNewsItem.Text = _Box1Name;
            TopNewsItem.Tag = _Box1URL;

            FavBox1.Tag = _Box1URL;
            HomeBox1.Tag = _Box1URL;
            EmailBox1.Tag = _Box1URL;
            TwitterBox1.Tag = _Box1URL;
            FacebookBox1.Tag = _Box1URL;

            FavBox2.Tag = _Box2URL;
            HomeBox2.Tag = _Box2URL;
            EmailBox2.Tag = _Box2URL;
            TwitterBox2.Tag = _Box1URL;
            FacebookBox2.Tag = _Box1URL;

            FavBox3.Tag = _Box3URL;
            HomeBox3.Tag = _Box3URL;
            EmailBox3.Tag = _Box3URL;
            TwitterBox3.Tag = _Box1URL;
            FacebookBox3.Tag = _Box1URL;  
        }

        private String BoxTextClip(String SomeText)
        {
            if (SomeText.Length > 35)
            {
                SomeText = SomeText.Substring(0, 35) + "..."; 
            }
            return SomeText;
        }
         
        private void ExecuteCall(String PhoneNumber)
        {
            PhoneCallTask task = new PhoneCallTask();
            task.PhoneNumber = PhoneNumber;
            task.Show();
        }

        /// <summary>
        /// news rss feed...
        /// </summary>
        /// <param name="RawXML"></param>
        private void ProcessXMLResults(String RawXML)
        { 
            XElement _xml;
            System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
            try
            { 
                _xml = XElement.Parse(RawXML);


                foreach (XElement value in _xml.Elements("channel"))
                { 
                    if (BlogLstBx.Items.Count > 0)
                    {
                        BlogLstBx.Items.Clear();
                    }

                    foreach (XElement value2 in value.Elements("item"))
                    {
                        RssItem _RssItem = new RssItem();
                        _RssItem.Title = value2.Element("title").Value;
                        _RssItem.Link = value2.Element("link").Value;
                        _RssItem.Img = ExtractImgFromHTML(value2.Element("description").Value);
                        _RssItem.Description = value2.Element("description").Value;

                        BlogLstBx.Items.Add(_RssItem);
                    }
                }   
            }
            catch { }
        }

        /// <summary>
        /// twitter cacheing
        /// </summary>
        /// <param name="RawXML"></param>
        //private void ProcessXMLTwitterResults(String RawXML)
        //{ 
        //    XElement _xml;
        //    System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
        //    try
        //    { 
        //        _xml = XElement.Parse(RawXML);
                 
        //        foreach (XElement value in _xml.Elements("channel"))
        //        {
        //            foreach (XElement value2 in value.Elements("item"))
        //            {
        //                RssItem _RssItem = new RssItem();
        //                _RssItem.Title = value2.Element("title").Value;
        //                _RssItem.Link = value2.Element("link").Value;
        //                _RssItem.Description = value2.Element("description").Value;

        //                TwitterLstBx.Items.Add(_RssItem);
        //            }
        //        } 
        //    } catch { } 
        //} 

        private void SaveToFavorites(String KeyValue)
        {
            String Temp = Tools.GetSetting("FavoritesList.index").ToString();
            if (String.IsNullOrEmpty(Temp))
            {
                Tools.SaveSetting("FavoritesList.index", KeyValue);
            }
            else
            {
                if (Temp.IndexOf(KeyValue) == -1)
                {
                    Temp += "^" + KeyValue;
                    Tools.SaveSetting("FavoritesList.index", Temp);
                }
            }
        }
         
        private void About_Click(object sender, EventArgs e)
        {
            _Vibration.Start(_ThisTime);

            try
            {
                MessageBox.Show(_AboutText, "About", MessageBoxButton.OK);
            }
            catch (Exception) { } 
            // go to about page
        }

        private void EmailNews_Click(object sender, RoutedEventArgs e)
        { 
            _Vibration.Start(_ThisTime); 

            String[] FreezeDriedItemArray = ReturnFreezeDriedArray(sender);

            Tools.SendEmail(FreezeDriedItemArray[1], _EmailSubjectPrefix + FreezeDriedItemArray[0]);
        }

        private void Last3NewsFavorites_Click(object sender, RoutedEventArgs e)
        {
            _Vibration.Start(_ThisTime);

            MenuItem ThisItem = sender as MenuItem;
              
            String FreezeDriedItem = ThisItem.Tag.ToString();
            String[] FreezeDriedItemArray = FreezeDriedItem.Split('^');

            // save data...
            String FavStoryKey = Tools.ScrubTitleToKey(FreezeDriedItemArray[0]) + ".fav";
            Tools.SaveSetting(FavStoryKey, FreezeDriedItem);

            // add to favorites 
            SaveToFavorites(FavStoryKey); 
        }

        private void Last3NewsPin_Click(object sender, RoutedEventArgs e)
        {
            _Vibration.Start(_ThisTime);

            MenuItem ThisItem = sender as MenuItem;

            String FreezeDriedItem = ThisItem.Tag.ToString();
            String[] FreezeDriedItemArray = FreezeDriedItem.Split('^');

            // save data...
            String FavStoryKey = Tools.ScrubTitleToKey(FreezeDriedItemArray[0]) + ".fav";
            Tools.SaveSetting(FavStoryKey, FreezeDriedItem);
             
            // pin news item
            ShellTile SecondTile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("/NewsItem.xaml?FD=" + FavStoryKey));

            StandardTileData NewTileData = new StandardTileData();

            NewTileData.Title = FreezeDriedItemArray[0];
            NewTileData.BackgroundImage = new Uri("Resources/News.jpg", UriKind.Relative);
            NewTileData.Count = 0;
            NewTileData.BackTitle = _NewTileBackTitle;
            NewTileData.BackBackgroundImage = new Uri("Resources/Icon.Daily.jpg", UriKind.Relative);

            if (SecondTile == null)
            {
                ShellTile.Create(new Uri("/NewsItem.xaml?FD=" + FavStoryKey, UriKind.Relative), NewTileData);
            }
            else
            {
                SecondTile.Update(NewTileData);
            }

            // add to favorites 
            SaveToFavorites(FavStoryKey); 
        }

        private void TwitterBox_Click(object sender, RoutedEventArgs e)
        {
            _Vibration.Start(_ThisTime); 

            String[] FreezeDriedItemArray = ReturnFreezeDriedArray(sender);

            Tools.SendTwitter(FreezeDriedItemArray[1], FreezeDriedItemArray[0], TwitterHandle); 
        }

        private void FacebookBox_Click(object sender, RoutedEventArgs e)
        {
            _Vibration.Start(_ThisTime); 

            String[] FreezeDriedItemArray = ReturnFreezeDriedArray(sender);

            Tools.SendToFacebook(FreezeDriedItemArray[1], FreezeDriedItemArray[0]);
        } 

        private String [] ReturnFreezeDriedArray(object sender)
        { 
            MenuItem ThisItem = sender as MenuItem;

            String FreezeDriedItem = ThisItem.Tag.ToString();

            return FreezeDriedItem.Split('^'); 
        }

        private void TweeterFacebookBox_Click(object sender, RoutedEventArgs e)
        {
            _Vibration.Start(_ThisTime);

            String[] FreezeDriedItemArray = ReturnFreezeDriedArray(sender);

            Tools.SendToFacebook(String.Empty, "@" + FreezeDriedItemArray[0]);
        }

        private void ReTwitterBox_Click(object sender, RoutedEventArgs e)
        {
            _Vibration.Start(_ThisTime);

            String[] FreezeDriedItemArray = ReturnFreezeDriedArray(sender);

            Tools.SendTwitter(String.Empty, "RT: @" + FreezeDriedItemArray[0], String.Empty); 
        }
    } 
}